<?php

// +----------------------------------------------------------------------

// | Description: 客户

// +----------------------------------------------------------------------

// | Author: zl

// +----------------------------------------------------------------------



namespace app\crm\controller;



use app\admin\controller\ApiCommon;

use app\crm\model\BalanceLog;

use app\crm\model\Setting;

use app\crm\model\SettingCategory;

use app\crm\model\Service;

use app\crm\model\ReturnVist;

use app\crm\model\ReturnVistT;

use app\crm\model\Customer as CustomerModel;

use app\crm\model\TransferShop;

use app\crm\model\CustomerConfig as CustomerConfigModel;

use app\crm\model\CustomerGrade as CustomerGradeModel;

use think\response\Json;

use think\facade\Db;

use think\facade\Request;

use app\admin\model\Coupon as CouponModel;

use app\common\traits\ActionRecordTrait;


class AddcustomerXinLingShou extends ApiCommon

{
    protected $customerModel;

    protected $customerConfigModel;

    /**

     * 用于判断权限

     * @permission 无限制

     * @allow 登录用户可访问

     * @other 其他根据系统设置

     **/

    public function initialize()

    {

        $action = [

            'permission' => ['add_customer_xinlingshou','add_customer_tuiguang'],

            'allow' => ['users', 'info']

        ];

        event('CheckAuth',$action);

        $request = $this->request;

        $a = strtolower($request->action());



        $this->customerModel = new CustomerModel();

        $this->customerConfigModel = new CustomerConfigModel();

        if (!in_array($a, $action['permission'])) {

            parent::initialize();

        }

    }

    /**
     * 更新客服
     */
    public function add_customer_xinlingshou(){

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/addCustomer_xinlingshou.html">返回【会员基本信息导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        $importData = readExcelData($tmp_name);

        // echo "<pre>";
        // print_r($importData);
        // echo "</pre>";
        // exit;

        
        $shopId = '73782774881835';

        $kefu_list = Db::name('admin_user')->where('structure_id','8')->column('id','realname');
        // echo "<pre>";
        // print_r($kefu_list);
        // echo "</pre>";

        $source_type = Db::name('setting')->where('category_id','4')->column('id','name');
        // echo "<pre>";
        // print_r($source_type);
        // echo "</pre>";
        // exit;

        $scar_type = Db::name('setting')->where('category_id','1')->column('id','name');
        // echo "<pre>";
        // print_r($scar_type);
        // echo "</pre>";

        $bw_list = Db::name('setting')->where('category_id','2')->column('id','name');
        // echo "<pre>";
        // print_r($bw_list);
        // echo "</pre>";
        // exit;

        $is_or_no = [
            '是' => 1,
            '否' => 2,
        ];

        $sex = [
            '男' => 1,
            '女' => 2,
        ];


        foreach ($importData as $key => $value) {
            if($value){
                $where = [];
                $kefu_id = $kefu_list[$value['0']] ?? '';
                $source_id = $source_type[$value['7']];
    
                $age = $value['10'] ?? '';
                $birthday = 0;
                if($age){
                    $birth_year = bcsub(date('Y'),$age);
                    $birth_mon = date('m');
    
                    $birthday = strtotime($birth_year.'-'.$birth_mon.'-01');
    
                    // echo "顾客生日是：".$birthday;
                }
    
                array_push($where,['shop_id','=',$shopId]);
                array_push($where,['telephone','=',$value['3']]);
    
                // exit;
    
                $customer_info = Db::name('customer')->where($where)->select()->toArray();
    
                if(count($customer_info)>0){
                    // echo "顾客已存在！";
    
                    $customerID = $customer_info[0]['id'];
    
                    $updateArr = [
                        'creator_id' => $kefu_id,
                        'operator'   => $kefu_id,
                        'source_id'  => $source_id,
                    ];
    
                    $bool = Db::name('customer')->where(['id' => $customerID])->update($updateArr);
                }else{
                    // echo "可以新增！";
                    $data = [
                        'shop_id'               => $shopId,
                        'customer_name'         => trim($value['2']),
                        'telephone'             => isset($value['3']) ? $value['3'] : '',
                        'repair_progress'       => '57',
                        'status'                => '1',
                        'source_id'             => $source_id,
                        'creator_id'            => $kefu_id,
                        'create_time'           => time(),
                        'operator'              => $kefu_id,
                        'effective_entry'       => $is_or_no[$value['8']] ?? 0,
                        'first_time'            => strtotime($value['9']) ?? 0,
                        'sex'                   => $sex[$value['4']] ?? 0,
                        'age'                   => $age,
                        'birthday'              => $birthday,
                    ];
    
                    // echo "<pre>";
                    // print_r($data);
                    // echo "</pre>";
                    // exit;
                    $customerId = Db::name('customer')->insertGetId($data);
    
                    if ($customerId) {
                        $insertAll = [
                            'customer_setting_id_type'     => $scar_type[$value['6']],
                            'customer_setting_id_position' => $bw_list[$value['5']],
                            'customer_id'                  => $customerId,
                        ];
    
                        echo "<pre>";
                        print_r($insertAll);
                        echo "</pre>";
    
                        $scarID = Db::name('customer_scar')->insertGetId($insertAll);
                        
                        // 存储客户的余额信息
                        $customer_balanceAll = [
                            [
                                'shop_id'       => $shopId,
                                'customer_id'   => $customerId,
                                'balance_category_id'   => 1,
                            ],
                            [
                                'shop_id'       => $shopId,
                                'customer_id'   => $customerId,
                                'balance_category_id'   => 2,
                            ]
                        ];
    
                        // echo "<pre>";
                        // print_r($customer_balanceAll);
                        // echo "</pre>";
    
                        $res = Db::name('customer_balance')->where('customer_id','=',$customerId)->select()->toArray();
                        if(!$res){
                            Db::name('customer_balance')->insertAll($customer_balanceAll);
                        }
                        
    
                    }
                }
                //-----------------------------------------------------------------------------------------------------------------------
            }
            
        }

        exit;
        echo '添加成功！！！<br><br><a href="http://sunburn.178590.com/return/addCustomer_xinlingshou.html">返回【客户信息导入】页面</a>';exit;
        
    }


    public function add_customer_tuiguang(){

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/add_customer_tuiguang.html">返回【会员基本信息导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        $importData = readExcelData($tmp_name);

        $shop_Id = '74076159037951'; // 营销中心

        $kefu_list = Db::name('admin_user')->where('structure_id','8')->column('id','realname');

        $source_type = Db::name('setting')->where('category_id','4')->column('id','name');
        // echo "<pre>";
        // print_r($source_type);
        // echo "</pre>";
        // exit;

        $repeatCustomer = [];

        // $deleteIds = [];

        foreach ($importData as $key => $value) {

            if($value){

                $where = [];

                // array_push($where,['shop_id','=',$shop_Id]);

                array_push($where,['telephone','=',$value['3']]);

                $customer_info = Db::name('customer')->where($where)->select()->toArray();

                if(count($customer_info)>0){
                    // echo "顾客已存在！";
                    $one = [];

                    $one['customer_name'] = trim($value['2']);

                    $one['telephone'] = $value['3'];

                    $one['kefu'] = $value['0'];

                    $one['ly'] = $value['7'];

                    array_push($repeatCustomer,$one);

                }else{

                    $kefu_id = $kefu_list[$value['0']] ?? '';

                    $data = [
                        'shop_id'               => $shop_Id,
                        'customer_name'         => trim($value['2']),
                        'telephone'             => isset($value['3']) ? $value['3'] : '',
                        'repair_progress'       => '57',
                        'status'                => '1',
                        'creator_id'            => $kefu_id,
                        'create_time'           => time(),
                        'operator'              => $kefu_id,
                        'source_id'             => $source_type[$value['7']] ?? '',
                    ];

                    $customerId = Db::name('customer')->insertGetId($data);

                    if ($customerId) {

                        // 存储客户的余额信息
                        $customer_balanceAll = [
                            [
                                'shop_id'       => $shop_Id,
                                'customer_id'   => $customerId,
                                'balance_category_id'   => 1,
                            ],
                            [
                                'shop_id'       => $shop_Id,
                                'customer_id'   => $customerId,
                                'balance_category_id'   => 2,
                            ]
                        ];

                        $res = Db::name('customer_balance')->where('customer_id','=',$customerId)->select()->toArray();

                        if(!$res){

                            Db::name('customer_balance')->insertAll($customer_balanceAll);

                        }

                    }

                }

                

            }

        }

        // if($deleteIds){

        //     echo "<pre>";
        //     print_r($deleteIds);
        //     echo "</pre>";

        //     $delete_where = [];

        //     array_push($delete_where,['id','in',$deleteIds]);

        //     Db::name('customer')->where($delete_where)->delete();

        // }

        if($repeatCustomer){

            $callName = [

                'customer_name'   =>'姓名',
    
                'telephone' =>'手机',
    
                'kefu' =>'客服',

                'ly' =>'来源',

            ];
    
            $downUrl = exportExcelData('新增重复顾客导出',$callName,$repeatCustomer,'xlsx',1);
    
            echo "<script language='javascript'>";
    
            echo " location='".$downUrl."';";
    
            echo "</script>"; 

        }
        

    }


    public function is_goods(){

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/add_customer_tuiguang.html">返回【会员基本信息导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        $importData = readExcelData($tmp_name);

        echo "<pre>";
        print_r($importData);
        echo "</pre>";
    }

}